const { quickMd5, getDate } = require("../utils/index");
const { success } = require("../utils/jsonResult");
const jwt = require("jsonwebtoken");
const {
  selectOneWhere,
  selectTotal,
  selectPage,
  select,
  insert,
  update,
  updateField,
  remove,
} = require("../model/userModel");
const { getUserRoleListByUserId } = require("./userRoleServices");
const { getRoleMenuListByRoleIds } = require("./roleMenuServices");
const { getMenuListByIds, getMenuList } = require("./menuServices");

class UserServices {
  constructor() {}
  async getUserPermission(userId) {
    try {
      const userRoleResult = await getUserRoleListByUserId(userId);
      const userRoleList= userRoleResult.data
      const roleIdArr = [];
      const menuIdArr = [];
      userRoleList.forEach(async (element) => {
        const roleId = element.role_id;
        roleIdArr.push(roleId);
      });
      if (roleIdArr.length <= 0) {
        return success("授权菜单列表");
      }
      const roleIds = roleIdArr.join(",");
      const roleMenuResult = await getRoleMenuListByRoleIds(roleIds);
      const roleMenuList = roleMenuResult.data;
      roleMenuList.forEach((element) => {
        const menuId = element.menu_id;
        const index = menuIdArr.indexOf(menuId);
        if (index == -1) {
          menuIdArr.push(menuId);
        }
      });
      if (menuIdArr.length <= 0) {
        return success("授权菜单列表");
      }
      const menuListResult = await getMenuList();
      const menuList = menuListResult.data;

      const menuIdArrNew = [];
      menuIdArr.forEach((menuId) => {
        const menu = menuList.find((x) => {
          return x.id === menuId;
        });
        if (!menu) {
          return;
        }
        menuIdArrNew.push(menuId);
        const pId = menu?.p_id;
        const index = menuIdArrNew.indexOf(pId);
        if (pId !== 0 && index === -1) {
          menuIdArrNew.push(pId);

          const parentMenu = menuList.find((x) => {
            return x.id === pId;
          });
          if (!parentMenu) {
            return;
          }
          const pId1 = parentMenu.p_id;
          const index1 = menuIdArrNew.indexOf(pId1);
          if (pId1 !== 0 && index1 === -1) {
            menuIdArrNew.push(pId1);
          }
        }
      });
      const menuIds = menuIdArrNew.join(",");
      const list = await getMenuListByIds(menuIds);
      return list;
    } catch (error) {
      throw error;
    }
  }
  async userLogin(loginInfo) {
    try {
      const { userName, userPassword } = loginInfo;
      const fields = ["user_name"];
      const values = [userName];
      const result = await selectOneWhere(fields, values);
      const user = result.results && result.results[0];
      const password = user && user.password;
      const passwordMd5 = quickMd5(userPassword);
      if (password !== passwordMd5) {
        throw error;
      } else {
        const token = jwt.sign({ id:user.id,userName:user.userName }, "quick", {
          expiresIn: 1000 * 60 * 5,
        }); //过期时间5分
        return success("登录成功", {
          token: token,
        });
      }
    } catch (error) {
      throw error;
    }
  }
  async getUserPageList(current, size, userName) {
    try {
      let pageIndex = 1;
      let pageSize = 10;
      if (current < 1) {
        current = 1;
      }
      if (size < 1) {
        size = 10;
      }
      current = parseInt(current);
      size = parseInt(size);
      pageIndex = size * (current - 1);
      pageSize = size;
      const pageListResult = await selectPage(pageIndex, pageSize, userName);
      const pageList = pageListResult.results && pageListResult.results;
      const totalResult = await selectTotal(userName);
      const total = totalResult.results && totalResult.results[0].total;
      return success("订单分页列表", pageList, {
        current,
        size,
        total,
      });
    } catch (error) {
      throw error;
    }
  }
  async getUserList() {
    try {
      const result = await select();
      const user = result.results && result.results;
      return success("用户列表", user);
    } catch (error) {
      throw error;
    }
  }
  async getUserDetail(id) {
    try {
      const fields = ["id"];
      const values = [id];
      const result = await selectOneWhere(fields, values);
      const user = result.results && result.results[0];
      return success("用户详情", user);
    } catch (error) {
      throw error;
    }
  }
  async getUserInfo(userName) {
    try {
      const fields = ["user_name"];
      const values = [userName];
      const result = await selectOneWhere(fields, values);
      const user = result.results && result.results[0];
      return success("登录用户信息", user);
    } catch (error) {
      throw error;
    }
  }
  async addUser(user) {
    try {
      user.password = quickMd5(quickMd5("123456")); //初始密码123456，密码两次加密，代表前端一次，后端一次
      user.create_time = getDate();
      await insert(user);
      return success("添加用户成功");
    } catch (error) {
      throw error;
    }
  }
  async updateUser(user) {
    try {
      await update(user);
      return success("修改用户成功");
    } catch (error) {
      throw error;
    }
  }
  async removeUser(id) {
    try {
      await remove(id);
      return success("删除用户成功");
    } catch (error) {
      throw error;
    }
  }
  async batchRemoveUser(ids) {
    try {
      await remove(ids);
      return success("删除用户成功");
    } catch (error) {
      throw error;
    }
  }
  async updateUserPassword(user) {
    try {
      let password = quickMd5(user.newPassword);
      const fields = ["password"];
      const values = [password];
      await updateField(user.id, fields, values);
      return success("修改用户密码成功");
    } catch (error) {
      throw error;
    }
  }
  async resetUserPassword(id) {
    try {
      let password = quickMd5(quickMd5("123456")); //初始密码123456，密码两次加密，代表前端一次，后端一次
      const fields = ["password"];
      const values = [password];
      await updateField(id, fields, values);
      return success("重置用户密码成功");
    } catch (error) {
      throw error;
    }
  }
  async enabledUser(id) {
    try {
      const fields = ["enabled"];
      const values = [0];
      await updateField(id, fields, values);
      return success("启用用户成功");
    } catch (error) {
      throw error;
    }
  }
  async disableUser(id) {
    try {
      const fields = ["enabled"];
      const values = [1];
      await updateField(id, fields, values);
      return success("禁用用户成功");
    } catch (error) {
      throw error;
    }
  }
}
module.exports = new UserServices();
